package cn.iocoder.yudao.framework.redis.config;

import cn.hutool.core.util.ReflectUtil;
import cn.iocoder.yudao.framework.redis.core.RedisEventListener;
import cn.iocoder.yudao.framework.redis.core.RedisPublishClient;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.redisson.spring.starter.RedissonAutoConfigurationV2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.data.redis.serializer.RedisSerializer;

/**
 * Redis 配置类
 */
@AutoConfiguration(before = RedissonAutoConfigurationV2.class) // 目的：使用自己定义的 RedisTemplate Bean
public class YudaoRedisAutoConfiguration {

  @Value("${spring.data.redis.host}")
  private String redisHost;

  @Value("${spring.data.redis.port}")
  private int redisPort;

  @Value("${spring.data.redis.database}")
  private int database;

  @Value("${spring.data.redis.password}")
  private String password;

  @Bean
  public MessageListenerAdapter messageListener(ApplicationContext context) {
    return new MessageListenerAdapter(new RedisEventListener(context));
  }

  @Bean
  public RedisMessageListenerContainer redisContainer(RedisConnectionFactory factory, ApplicationContext context) {
    final RedisMessageListenerContainer container = new RedisMessageListenerContainer();
    container.setConnectionFactory(factory);
    container.addMessageListener(messageListener(context),
        new ChannelTopic(RedisPublishClient.COMMON_REDIS_EVENT_CHANNEL));
    return container;
  }

  @Bean
  public RedisPublishClient redisPublishClient() {
    return new RedisPublishClient();
  }

  @Bean
  public LettuceConnectionFactory lettuceConnectionFactory() {
    final RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration(redisHost, redisPort);
    configuration.setDatabase(database);
    configuration.setPassword(password);
    return new LettuceConnectionFactory(configuration);
  }

  /**
   * 创建 RedisTemplate Bean，使用 JSON 序列化方式
   */
  @Bean
  public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory factory) {
    // 创建 RedisTemplate 对象
    RedisTemplate<String, Object> template = new RedisTemplate<>();
    // 设置 RedisConnection 工厂。😈 它就是实现多种 Java Redis 客户端接入的秘密工厂。感兴趣的胖友，可以自己去撸下。
    template.setConnectionFactory(factory);
    // 使用 String 序列化方式，序列化 KEY 。
    template.setKeySerializer(RedisSerializer.string());
    template.setHashKeySerializer(RedisSerializer.string());
    // 使用 JSON 序列化方式（库是 Jackson ），序列化 VALUE 。
    template.setValueSerializer(buildRedisSerializer());
    template.setHashValueSerializer(buildRedisSerializer());
    return template;
  }

  public static RedisSerializer<?> buildRedisSerializer() {
    RedisSerializer<Object> json = RedisSerializer.json();
    // 解决 LocalDateTime 的序列化
    ObjectMapper objectMapper = (ObjectMapper) ReflectUtil.getFieldValue(json, "mapper");
    objectMapper.registerModules(new JavaTimeModule());
    return json;
  }

}
